package com.ningmengs789.live.ui.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.ningmengs789.live.R;
import com.ningmengs789.live.SealAppContext;
import com.ningmengs789.live.http.JsonBuilder;
import com.ningmengs789.live.http.OKHttpUtils;
import com.ningmengs789.live.Interface.RequestCallback;
import com.ningmengs789.live.live.live.common.utils.DialogUitl;
import com.ningmengs789.live.message.ChatPresenter;
import com.ningmengs789.live.message.ConversationFactory;
import com.ningmengs789.live.message.MessageFactory;
import com.ningmengs789.live.message.db.IMConversation;
import com.ningmengs789.live.message.db.IMConversationDB;
import com.ningmengs789.live.message.db.MessageDB;
import com.ningmengs789.live.message.interf.ChatViewIF;
import com.ningmengs789.live.message.ui.models.MediaMessage;
import com.ningmengs789.live.net.response.LaunchChatResponse;
import com.ningmengs789.live.net.utils.json.JsonMananger;
import com.ningmengs789.live.ui.fragment.TaskFragment;
import com.ningmengs789.live.utils.CommonUtils;
import com.ningmengs789.live.utils.IPermissions;
import com.ningmengs789.live.utils.PermissionsUtils;
import com.ningmengs789.live.net.network.http.HttpException;
import com.ningmengs789.live.net.response.ChatTaskListResponse;
import com.ningmengs789.live.net.utils.NToast;
import com.ningmengs789.live.server.widget.BottomMenuDialogQL;
import com.ningmengs789.live.server.widget.LoadDialog;
import com.ningmengs789.live.server.widget.PromptPopupDialog;
import com.ningmengs789.live.ui.widget.MorePopWindow;
import com.ningmengs789.live.ui.widget.dialogorPopwindow.TaskAlertDialog;
import com.ningmengs789.live.utils.UserInfoUtil;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMMessage;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

public class TaskLobbyActivity extends BaseActivity implements ChatViewIF, IPermissions {

    @BindView(R.id.tv_title_center)
    TextView tv_title_center;
    @BindView(R.id.text_right)
    TextView text_right;

    private Context mContext;

    private int type = 3;//聊天类型（1:文字 2:语音 3:视频）
    private TaskFragment mTaskFragment;

    private String mTencentId;
    private String mNmae;
    private String mAvatar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isShow = true;
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_o_chat);

        ButterKnife.bind(this);
        setHeadLayout();

        mTencentId = UserInfoUtil.getMiTencentId();
        mNmae = UserInfoUtil.getName();
        mAvatar = UserInfoUtil.getAvatar();

        PermissionsUtils.initPermission(mContext);
        init();
    }

    private void init(){
        tv_title_center.setVisibility(View.VISIBLE);
        tv_title_center.setText(R.string.rw_dt);
        text_right.setVisibility(View.VISIBLE);
        text_right.setText(R.string.release_task);

        mTaskFragment = new TaskFragment();
        addFragment(R.id.activity_o_chat_fl, mTaskFragment, "TaskFragment");

        text_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MorePopWindow morePopWindow = new MorePopWindow(TaskLobbyActivity.this, new MorePopWindow.VoiceClickListener() {
                    @Override
                    public void onVoiceClick() {
                        type = 2;
                        getCostList();

                    }
                }, new MorePopWindow.VideoClickListener() {
                    @Override
                    public void onVideoClick() {
                        type = 3;
                        getCostList();
                    }
                });
                morePopWindow.showPopupWindow(text_right);
            }
        });
    }

    protected void addFragment(int containerViewId, Fragment fragment, String tag) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        // 设置tag，不然下面 findFragmentByTag(tag)找不到
        fragmentTransaction.add(containerViewId, fragment, tag);
        fragmentTransaction.addToBackStack(tag);
        fragmentTransaction.commit();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void publishChatTask(){
        String body = "";
        try {
            body = new JsonBuilder()
                    .put("per_cost", per_cost)
                    .put("type", type)
                    .build();
        } catch (JSONException e) {
        }
        OKHttpUtils.getInstance().getRequest("app/task/publishChatTask", body, new RequestCallback() {
            @Override
            public void onError(int errCode, String errInfo) {
                LoadDialog.dismiss(mContext);
                if (errCode == 201) {//音浪不足
                    PromptPopupDialog.newInstance(mContext,
                            "",
                            errInfo,
                            getString(R.string.recharge))
                            .setPromptButtonClickedListener(new PromptPopupDialog.OnPromptButtonClickedListener() {
                                @Override
                                public void onPositiveButtonClicked() {
                                    Intent intent = new Intent(mContext, MyWalletActivity1.class);
                                    intent.putExtra("currentItem",0);
                                    startActivity(intent);
                                    overridePendingTransition(R.anim.slide_right_entry, R.anim.hold);
                                }
                            }).setLayoutRes(R.layout.recharge_popup_dialog).show();
                } else{
                    DialogUitl.showSimpleHintDialog(mContext,
                            getString(R.string.prompt),
                            getString(R.string.confirm),
                            getString(R.string.cancel),
                            errInfo,
                            true,
                            true,
                            new DialogUitl.SimpleCallback2() {
                                @Override
                                public void onCancelClick() {
                                }
                                @Override
                                public void onConfirmClick(Dialog dialog, String content) {
                                    dialog.dismiss();
                                }
                            });
                }
            }
            @Override
            public void onSuccess(String result) {
                LoadDialog.dismiss(mContext);
                if (mTaskFragment != null){
                    mTaskFragment.taskList();
                }
            }
        });
    }

    //2:语音 3:视频
    private void getCostList(){
        String body = "";
        try {
            body = new JsonBuilder()
                    .put("type", type)
                    .build();
        } catch (JSONException e) {
        }
        OKHttpUtils.getInstance().getRequest("app/task/getCostList"/*"app/user/getCostList"*/, body, new RequestCallback() {
            @Override
            public void onError(int errCode, String errInfo) {
                NToast.shortToast(mContext, errInfo);
            }
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject data = new JSONObject(result);
                    JSONArray list = data.getJSONArray("list");
                    priceList.clear();
                    for (int i = 0; i < list.length(); i++) {
                        priceList.add(list.getInt(i));
                    }

                    getSendCost();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getSendCost(){
        String body = "";
        try {
            body = new JsonBuilder()
                    .put("type", type)
                    .build();
        } catch (JSONException e) {
        }
        OKHttpUtils.getInstance().getRequest("app/task/getSendCost", body, new RequestCallback() {
            @Override
            public void onError(int errCode, String errInfo) {
                NToast.shortToast(mContext, errInfo);
            }
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject data = new JSONObject(result);
                    send_task_cost = data.getString("send_task_cost");
                    showPhotoDialog(type);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private String send_task_cost;

    private void launchChat4ChatTask(int id){
        String body = "";
        try {
            body = new JsonBuilder()
                    .put("task_id", task_id_v_)
                    .put("accept_uid", id)
                    .put("type", mListBean.getTask_type())
                    .put("robot_id", id)
                    .build();
        } catch (JSONException e) {
        }
        OKHttpUtils.getInstance().getRequest("app/task/launchChat4ChatTask", body, new RequestCallback() {
            @Override
            public void onError(int errCode, String errInfo) {
                LoadDialog.dismiss(mContext);
                shoeHintDialog(errInfo, errCode);
            }
            @Override
            public void onSuccess(String result) {
                LoadDialog.dismiss(mContext);
                try {
                    LaunchChatResponse response = JsonMananger.jsonToBean(result, LaunchChatResponse.class);
                    response_(response);
                } catch (HttpException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private ChatTaskListResponse.ListBean mListBean;

    @Override
    public void allPermissions() {
        //TODO
        //TODO
        //TODO
        if (mListBean.getUser_list() == null || mListBean.getUser_list().size() <= 0){
            NToast.shortToast(mContext, "无人接任务");
        }else {
            DialogUitl.showStringArrayDialog22(mContext, mListBean, new DialogUitl.StringArrayDialogCallback22() {
                @Override
                public void onItemClick(ChatTaskListResponse.ListBean.UserListBean bean) {
                    request_0_0(bean);
                }
            });
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionsUtils.onRequestPermissionsResult(requestCode, permissions, grantResults, this, this, true);
    }

    public void request_(ChatTaskListResponse.ListBean listBean){
        mListBean = listBean;
        PermissionsUtils.onResume(TaskLobbyActivity.this, TaskLobbyActivity.this);
    }

    //type 1 语音 2视频
    private void request_0_0(ChatTaskListResponse.ListBean.UserListBean bean){
        if (mListBean == null){
            return;
        }

        int user_id = bean.getId();
        String name = bean.getUser_nickname();
        String avatar = CommonUtils.getUrl(bean.getAvatar());

        if (mTencentId.equals(String.valueOf(user_id))){
            //自己不能跟自己聊天
            return;
        }

        chatPresenter = new ChatPresenter(this, String.valueOf(user_id), TIMConversationType.C2C);

        imConversation = new IMConversation();
        imConversation.setType(0);// 0 单聊  1 群聊  2 系统消息

        imConversation.setUserIMId(mTencentId);
        imConversation.setUserId(mTencentId);

        imConversation.setOtherPartyIMId(String.valueOf(user_id));
        imConversation.setOtherPartyId(String.valueOf(user_id));

        imConversation.setUserName(mNmae);
        imConversation.setUserAvatar(mAvatar);

        imConversation.setOtherPartyName(name);
        imConversation.setOtherPartyAvatar(avatar);

        imConversation.setConversationId(imConversation.getUserId() + "@@" + imConversation.getOtherPartyId());

        task_id_v_ = mListBean.getTask_id();
        launchChat4ChatTask(user_id);
    }

    private ChatPresenter chatPresenter;
    private IMConversation imConversation;
    private int task_id_v_;

    public void response_(LaunchChatResponse response){
        //-1 无限聊天 >0剩余可聊时间
        //0 没钱了
        /*RoomActivity.order_no = null;
        RoomActivity.rest_time = 0;
        int rest_time = response.getRest_time();
        if (rest_time == 0){
            shoeHintDialog("音浪不足", 201);
        }else {
            RoomActivity.order_no = response.getOrder_no();
            RoomActivity.rest_time = rest_time;
            MediaMessage imageMessage;
            //roomdbId 存入数据库,判断本次通话是否保存 正常 传时间戳 唯一
            //roomId 云通信的房间号
            //type 1 语音  2 视频
            //isHangup 默认 0 接收通话  1 挂断通话
            if (type_v_ == 2){
                imageMessage = new MediaMessage(String.valueOf(System.currentTimeMillis()), response.getHome_id(),
                        1,0, 0, imConversation);
                chatPresenter.sendMessage(imageMessage.getMessage(), null, false);
            }else if (type_v_ == 3){
                imageMessage = new MediaMessage(String.valueOf(System.currentTimeMillis()), response.getHome_id(),
                        2,0, 0, imConversation);
                chatPresenter.sendMessage(imageMessage.getMessage(), null, false);
            }
        }*/

        String order_no = response.getOrder_no();
        String consumerUserid = mTencentId;/*response.getCost_uid();*/
        MediaMessage imageMessage;
        //roomdbId 存入数据库,判断本次通话是否保存 正常 传时间戳 唯一
        //roomId 云通信的房间号
        //type 1 语音  2 视频
        //isHangup 默认 0 接收通话  1 挂断通话
        if (mListBean.getTask_type() == 2) {
            imageMessage = new MediaMessage(String.valueOf(System.currentTimeMillis()), response.getHome_id(),
                    1, 0, response.getSpeech_cost(), order_no, consumerUserid, imConversation);
            chatPresenter.sendMessage(imageMessage.getMessage(), null, false);
        } else if (mListBean.getTask_type() == 3) {
            imageMessage = new MediaMessage(String.valueOf(System.currentTimeMillis()), response.getHome_id(),
                    2, 0, response.getVideo_cost(), order_no, consumerUserid, imConversation);
            chatPresenter.sendMessage(imageMessage.getMessage(), null, false);
        }

            /*RoomActivity.order_no = response.getData().getOrder_no();
            MediaMessage imageMessage;
            int home_id = response.getData().getHome_id();
            //roomdbId 存入数据库,判断本次通话是否保存 正常 传时间戳 唯一
            //roomId 云通信的房间号
            //type 1 语音  2 视频
            //isHangup 默认 0 接收通话  1 挂断通话
            if (type_v_ == 2){
                imageMessage = new MediaMessage(String.valueOf(System.currentTimeMillis()), home_id,
                        1,0, 0, imConversation);
                chatPresenter.sendMessage(imageMessage.getMessage(), null, false);
            }else if (type_v_ == 3){
                imageMessage = new MediaMessage(String.valueOf(System.currentTimeMillis()), home_id,
                        2,0, 0, imConversation);
                chatPresenter.sendMessage(imageMessage.getMessage(), null, false);
            }*/
    }

    private void shoeHintDialog(String msg, int code){
        if (code == 201){
            PromptPopupDialog.newInstance(this,
                    "",
                    msg,
                    getString(R.string.recharge))
                    .setPromptButtonClickedListener(new PromptPopupDialog.OnPromptButtonClickedListener() {
                        @Override
                        public void onPositiveButtonClicked() {
                            Intent intent = new Intent(mContext, MyWalletActivity1.class);
                            intent.putExtra("currentItem",0);
                            startActivity(intent);
                            overridePendingTransition(R.anim.slide_right_entry, R.anim.hold);
                        }
                    }).setLayoutRes(R.layout.recharge_popup_dialog).show();
        }else{
            DialogUitl.showSimpleHintDialog(this, getString(R.string.prompt), msg,
                    true, new DialogUitl.SimpleCallback() {
                        @Override
                        public void onConfirmClick(Dialog dialog, String content) {
                            dialog.dismiss();
                        }
                    });
        }
    }

    @Override
    public void updateMessage(MessageDB messageDB) {

    }

    @Override
    public void onSendMessageFail(int code, String desc, TIMMessage message) {
//        IMConversationDB imConversationDB = ConversationFactory.getMessage(message, true);
        MessageDB messageDB = MessageFactory.getMessage(message, true);

        if (messageDB != null && messageDB.getType() == 10){
            NToast.shortToast(mContext, "发送失败 请检测您的网络~");
            return;
        }
    }

    @Override
    public void onSuccess(TIMMessage message) {
        IMConversationDB imConversationDB = ConversationFactory.getMessage(message, true);
        MessageDB messageDB = MessageFactory.getMessage(message, true);

        if (messageDB != null && messageDB.getType() == 10){
            SealAppContext.getInstance().mediaMessage(imConversationDB, messageDB, true);
            return;
        }
    }

    /////////////////////////////////////////////////////////
    private BottomMenuDialogQL dialog;
    private int per_cost;

    private void showPhotoDialog(int type) {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        if (priceList.size() == 0){
            return;
        }
        dialog = new BottomMenuDialogQL(mContext, type, String.valueOf(priceList.get(0)), send_task_cost);
        dialog.setConfirmListener(new BottomMenuDialogQL.ConfirmListener() {
            @Override
            public void onClick(String cost) {
                per_cost = Integer.parseInt(cost);
                dialog.dismiss();
                LoadDialog.show(mContext);

                publishChatTask();
            }
        });
        dialog.setCostListener(new BottomMenuDialogQL.CostListener() {
            @Override
            public void onClick(TextView costTv) {
                popupDialog(costTv);
            }
        });
//        dialog.setCancelable(false);
        dialog.show();
    }

    private void popupDialog(final TextView costTv){
        final TaskAlertDialog priceAlertDialog = new TaskAlertDialog(this);
        priceAlertDialog.setData(priceList);
        priceAlertDialog.setTiTle(getString(R.string.task_1));
        priceAlertDialog.builder();
        priceAlertDialog.setNegativeButton(getString(R.string.cancel), new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        priceAlertDialog.setPositiveButton(getString(R.string.confirm), new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String str = priceAlertDialog.getPriceStr();
                costTv.setText(str);
            }
        });
        priceAlertDialog.show();
    }

    private ArrayList<Integer> priceList = new ArrayList<>();

}
